﻿<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
require_once (APPPATH . 'libraries/categoryobject.php');
require_once (APPPATH . 'libraries/producttypeobject.php');

/*
 *	global variable to store categories, it is used to build dynamic menu
 *
 * 	IMPORTANT: remember to update this variable when:
 * 	1. Insert/Delete/Update a category
 * 	2. Insert/Delete/Update a product type
 *
 */

/**
 * Category_Model class: accessing database
 */
class Category_Model extends CI_Model
{
	private static $instance;
	private $_categories;
	
	function __construct()
	{
		parent::__construct();

		$this->_categories = array();
		self::$instance =& $this;
	}
	
	public static function getInstance()
	{
		return self::$instance;
	}
	
	public function getStorageCategories()
	{
		if (count($this->_categories) == 0)
			$this->getAllCategories();
		
		return $this->_categories;
	}
	
	private function countCategory()
	{
		return $this->db->count_all(CATEGORIES_TABLE);
	}

	public function getAllCategories()
	{
		$categories = array();
		$this->db->order_by('_order');
		$query = $this->db->get(CATEGORIES_TABLE);

		foreach ($query->result() as $row)
		{
			// Query product types corresponding to category
			$productTypes = $this->producttype_model->getProductTypesByCategoryId($row->id);


			$category = new CategoryObject($row->id, $row->title, $productTypes, $row->_order, $row->description, $row->image);
			$categories[] = $category;
			$this->_categories[] = $category;
		}

		return $categories;
	}

	/*
	 Insert new category
	 * 	return TRUE if insert success, FALSE if insert failed
	 */
	public function insertCategory($title, $description, $image)
	{
		$query = "INSERT INTO " . CATEGORIES_TABLE . " VALUES(NULL, ?, ?, ?, ?)";

		$this->db->trans_start();
		$order = $this->countCategory() + 1;
		$this->db->query($query, array($title, $order, $description, $image));
		$this->db->trans_complete();

		if ($this->db->trans_status() === FALSE)
			return INSERT_ERROR;
		
		// Update global variable: need to check performance
		$this->getAllCategories();

		return ERROR_NONE;
	}
	
	public function updateCategory($id, $category)
	{
		$query = "UPDATE " . CATEGORIES_TABLE . " SET title=?, _order=?, description=?, image=? WHERE id=?";

		$this->db->trans_start();
		$this->db->query($query, array($category->getTitle(), $category->getOrder(), $category->getDescription(), $category->getImage(), $id));
		$this->db->trans_complete();

		if ($this->db->trans_status() === FALSE)
			return UPDATE_ERROR;
		
		// Update global variable: need to check performance
		$this->getAllCategories();

		return ERROR_NONE;
	}

	/*
	 Delete an existing category
	 * 	return TRUE if delete success, FALSE if delete failed
	 */
	public function deleteCategory($id)
	{
		$query = "DELETE FROM " . CATEGORIES_TABLE . " WHERE id=?";

		$this->db->trans_start();
		$this->db->query($query, array($id));
		$this->db->trans_complete();

		if ($this->db->trans_status() === FALSE)
			return DELETE_ERROR;
		
		// Update global variable: need to check performance
		$this->getAllCategories();

		return ERROR_NONE;
	}
	
	public function updateOrder($ids, $orders)
	{
		$query = "UPDATE ".CATEGORIES_TABLE." SET _order = CASE id";
		$where = "(";
		
		for ($i = 0, $size = count($ids); $i < $size; $i++)
		{
			$query .= " WHEN ".$ids[$i]." THEN ".$orders[$i];
			$where .= $ids[$i];
			$where .= ($i < $size - 1) ? "," : "";
		}
		
		$where .= ")";
		$query .= " END WHERE id IN ".$where;
		
		$this->db->trans_start();
		$this->db->query($query, $ids);
		$this->db->trans_complete();
		
		if ($this->db->trans_status() === FALSE)
			return UPDATE_ERROR;
		
		return ERROR_NONE;
	}

	public function deleteMultipleCategories($ids)
	{
		$query = "";
		$size = count($ids);
		$query = "DELETE FROM " . CATEGORIES_TABLE . " WHERE id IN (";

		for ($i = 0; $i < ($size - 1); $i++)
		{
			$query .= "?, ";
		}

		$query .= "?)";

		$this->db->trans_start();
		$this->db->query($query, $ids);
		$this->db->trans_complete();

		if ($this->db->trans_status() === FALSE)
			return DELETE_ERROR;
		
		// Update global variable: need to check performance
		$this->getAllCategories();
		
		return ERROR_NONE;
	}

	public function getCategoryById($id)
	{
		$category = new CategoryObject();

		$this->db->where('id', $id);
		$data = $this->db->get(CATEGORIES_TABLE);

		if ($data->num_rows() > 0)
		{
			$row = $data->row();
			$category->setId($row->id);
			$category->setTitle($row->title);
			$category->setOrder($row->_order);
			$category->setDescription($row->description);
			$category->setImage($row->image);
		}
		return $category;
	}

	/*
	 Check if category exists or not
	 */
	public function isCategoryExisted_id($id)
	{
		$query = "SELECT id, title FROM " . CATEGORIES_TABLE . " WHERE id=?";
		$data = $this->db->query($query, array($id));

		return ($data->num_rows() > 0);
	}

	public function findCategory($title)
	{
		$id = -1;		$query = "SELECT id FROM " . CATEGORIES_TABLE . " WHERE title LIKE ?";
		$data = $this->db->query($query, array($this->db->escape_like_str($title)));
		
		if ($data->num_rows() > 0)
		{
			$row = $data->row();
			$id = $row->id;
		}

		return $id;
	}

}
?>